'use strict'

const { Controller } = require('egg')

class CommentController extends Controller {
  // 添加评论
  async createComment() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({
      leaveword_id: { type: 'int', required: true, desc: '留言的id' },
      content: { type: 'string', required: true, range: { min: 1, max: 100 }, desc: '评论内容' }
    })
    // 整理参数
    const { leaveword_id, content } = ctx.request.body
    const user_id = ctx.authUser.id
    const result = await app.model.Comment.create({ leaveword_id, content, user_id })
    ctx.apiSuccess(result)
  }
  // 获取评论列表
  async getComment() {
    const { ctx, service } = this
    // 参数验证
    ctx.validate({ leaveword_id: { type: 'int', required: true, desc: '留言的id' } })
    const { leaveword_id } = ctx.request.query
    const result = await service.comment.getComment(leaveword_id)
    ctx.apiSuccess(result)
  }
  // 删除评论
  async deleteComment() {
    const { ctx, app } = this
    // 参数验证
    ctx.validate({ ids: { type: 'string', required: true, desc: '评论id' } })
    let { ids } = ctx.request.body
    ids = ids.split(',').map((id) => parseInt(id))
    const result = await app.model.Comment.destroy({ where: { id: ids } })
    ctx.apiSuccess(result)
  }
}

module.exports = CommentController
